<template>
  <div class="app-container">

    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="folderName"
            placeholder="请输入文件夹名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
<!--          default-expand-all 展开所有节点 -->
          <el-tree
            :data="customFolder"
            :props="defaultCustomFolder"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            highlight-current
            @node-click="handleCustomFolderClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入姓名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="办公电话" prop="telephone">
            <el-input
              v-model="queryParams.telephone"
              placeholder="请输入办公电话"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="客户区域" prop="region">
            <el-input
              v-model="queryParams.region"
              placeholder="请输入客户区域"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
              <el-option
                v-for="dict in dict.type.custom_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="最后下单时间" label-width="100px">
            <el-date-picker
              v-model="daterangeLastOrderTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="业务员" prop="userId">
            <el-select v-model="queryParams.userId" filterable placeholder="请选择">
              <el-option
                v-for="user in userList"
                :key="user.userId"
                :label="user.nickName"
                :value="user.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <template>

          </template>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['basic:custom:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['basic:custom:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['basic:custom:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['basic:custom:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
        <el-table v-loading="loading" :data="customList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="${comment}" align="center" prop="id" v-if="false"/>
          <el-table-column label="姓名" align="center" prop="name" />
          <el-table-column label="手机" align="center" prop="mobile" />
          <el-table-column label="办公电话" align="center" prop="telephone" />
          <el-table-column label="客户区域" align="center" prop="region" />
          <el-table-column label="详细地址" align="center" prop="address" />
          <el-table-column label="类型" align="center" prop="type">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.custom_type" :value="scope.row.type"/>
            </template>
          </el-table-column>
          <el-table-column label="最后下单时间" align="center" prop="lastOrderTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastOrderTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属业务员" align="center" prop="nickName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basic:custom:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basic:custom:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改客户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机" />
        </el-form-item>
        <el-form-item label="办公电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入办公电话" />
        </el-form-item>
        <el-form-item label="客户区域" prop="region">
          <el-input v-model="form.region" placeholder="请输入客户区域" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="dict in dict.type.custom_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件夹" prop="folderId">
          <treeselect v-model="form.folderId" :options="folderOptions" :normalizer="normalizer" @input="folderChange" :show-count="true"
                      placeholder="选择文件夹"/>
        </el-form-item>
        <el-form-item label="业务员" prop="userId">
          <template>
            <el-select v-model="form.userId" filterable placeholder="请选择">
              <el-option
                v-for="user in userList"
                :key="user.userId"
                :label="user.nickName"
                :value="user.userId">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCustom, getCustom, delCustom, addCustom, updateCustom, listCustomFolder, getUserList} from "@/api/basic/custom";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Custom",
  dicts: ['custom_type'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户管理表格数据
      customList: [],
      // 弹出层标题
      title: "",
      folderName: undefined,
      // 是否显示弹出层
      open: false,
      // 所属业务员时间范围
      daterangeLastOrderTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        mobile: null,
        telephone: null,
        region: null,
        type: null,
        lastOrderTime: null,
        userId: null,
        folderId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name :[{required: true, message: '请输入', trigger: 'blur'}],
        folderId :[{required: true, message: '请输入', trigger: 'blur'}]
      },
      customFolder: [],
      defaultCustomFolder: {
        children: 'children',
        label: 'name'
      },
      userList: [],
      //文件夹树
      folderOptions: [],
    };
  },
  created() {
    this.getList();
    this.getCustomFolder();
    this.getUser();
  },
  watch: {
    // 根据名称筛选部门树
    folderName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    getUser() {
      getUserList().then(res => {
        this.userList = res.data.map(item => {
          return {
            userId: item.userId,
            nickName: item.nickName
          }
        })
      })
    },
    /** 获取物资文件夹 */
    getCustomFolder() {
      this.loading = true;
      listCustomFolder().then(response => {
        this.customFolder = response.data;
        this.folderOptions = response.data;
      });
      this.loading = false;
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /** 查询客户管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeLastOrderTime && '' != this.daterangeLastOrderTime) {
        this.queryParams.params["beginLastOrderTime"] = this.daterangeLastOrderTime[0];
        this.queryParams.params["endLastOrderTime"] = this.daterangeLastOrderTime[1];
      }
      listCustom(this.queryParams).then(response => {
        this.customList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        mobile: null,
        telephone: null,
        region: null,
        address: null,
        type: null,
        folderId: null,
        lastOrderTime: null,
        userId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeLastOrderTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCustom(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户管理编号为"' + ids + '"的数据项？').then(function() {
        return delCustom(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/custom/export', {
        ...this.queryParams
      }, `custom_${new Date().getTime()}.xlsx`)
    },
    /** 文件夹节点点击事件 */
    handleCustomFolderClick(data, node, event) {
      this.queryParams.folderId = data.id;
      this.handleQuery();
    },
    folderChange(value) {
      this.$nextTick(() => {
        this.$refs.form.validateField('folderId');
      })
    }
  }
};
</script>
